import dict from '../../api/dict'
import hotel from '../../api/hotel'
import { login,getLoginUser,regist } from "@/api/common";

// 公用的状态
const state = {
    loginId: 'zyz',
    loginPwd: '111111',
    loginStatus: false,
    userId: 0,
    userRoleId: 0,
    userRole: '',
    areaValue: 0,
    hotelValue: 0,
    hospitalValue: 0,
    searchAddr: '',
    areas:[],
    hospitals:[]
  }
  
const getters = {
    showUser: (state,getters) => {
        state.userRole+':'+state.loginId
    },
    hospitalsFilterByArea: (state, getters) => {
        if(state.areaValue<=0)
            return state.hospitals
        else {
            const hs = {}
            for(var i in state.hospitals) {
                hs[i] = state.hospitals[i].filter((item, index,arr)=>{
                    return item.fid==state.areaValue
                });
            }
            return hs            
        }
    },
}

const actions = {
    login({state, commit}, loginId,loginPwd) {
        if(loginId=='') {
            loginId = state.loginId
            loginPwd = state.loginPwd
        }
        login(loginId,loginPwd,
            loginInfo => {
                commit('loginOk',loginInfo)
            }
        )
    },
    changeAreaValue({state, commit}, value) {
        commit('setAreaValue', value)
    },
    changeHospitalValue({state, commit}, value) {
        commit('setHospitalValue', value)
    },
    changeSearchAddr({state, commit}, value) {
        commit('setSearchAddr', value)
    },
    getAreas({state, commit}) {
        if(state.areas.length<0) {
            dict.getAreas(
                (areas) => {commit('setAreas', areas)},
                () => {}
            )
        }  
    },
    getHospitals({state, commit}) {
        console.log('getHospitals');
        if(state.hospitals.length<=0) {
            hotel.getHospitalIndexBars(
                (hospitals) => {
                    commit('setHospitals', hospitals)
                    },
                () => {}
            )
        }       
    }
}

const mutations = {
    loginOk(state, loginInfo) {
        state.userId = loginInfo.userId
        state.userRole = loginInfo.userRole
        state.userRoleId = loginInfo.userRoleId
    },
    setAreas(state, areas) {
        state.areas = areas
    },
    setAreaValue(state, value) {
        state.areaValue = value
    },
    setHospitalValue(state, value) {
        state.hospitalValue = value
    },
    setSearchAddr(state, value) {
        state.searchAddr = value
    },
    setHospitals(state, hospitals) {
        state.hospitals = hospitals
    }
}

  
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
  }
  